import React, { Component } from 'react'
import ProductStyle from '../../product/product.module.sass'

import MonthTable from '../common_table/month_table'
import RiskTable from '../common_table/risk_table'

import BarCharts from '../charts/bar'
import LineCharts from '../charts/line'
import AreaChart from '../charts/area'

import shareHeader from '../details/shareHeader'

import CommontHeaders from '../details/detail_common_header'

import { message } from 'antd'
import { axios } from '../../../Utils/index'
import url from 'url'
import cookie from 'js-cookie'
import { chartsColors, areaColors } from '../../../Utils/charts_config/charts_config'
import AddModal from '../add_product/add_product_modal'
import echarts from 'echarts'

const weekOptions = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                width: 100,
                color: 'rgba(0, 0, 0, 0.1)'
            },
            z: -1
        },
        formatter: (value) => {
            let itemDesc = `${value[0].name}`
            value.forEach(item => {
                itemDesc += `<br /> ${item.marker} ${item.seriesName}：${item.value}%`
            })

            return itemDesc
        }
    },
    grid: {
        top: '50px',
        right: '46px',
        left: '46px',
        bottom: 54
    },
    xAxis: [{
        type: 'category',
        data: ['-1.00, -0.80', '-0.80, -0.60', '-0.60, -0.40', '-0.40, -0.20', '-0.20, 0.00', '0.00, 0.20', '0.40, 0.60', '0.60, 0.80', '0.80, 1.00'],
        axisLine: {
            show: true,
            lineStyle: {
                color: '#ccc'
            }
        },
        axisLabel: {
            margin: 10,
            color: '#999',
            show: true,
            textStyle: {
                fontSize: 14
            },
        },
    }],
    yAxis: [{
        name: '频数（%）',
        nameLocation: 'end',
        nameTextStyle: {
            color: '#999',
            align: 'left'
        },
        color: '#ccc',
        axisLabel: {
            show: true,
            typeStyle: {
                color: '#333'
            },
            color: '#999'
        },
        axisLine: {
            show: false,
            lineStyle: {
                color: '#666'
            }
        },
        splitLine: {
            lineStyle: {
                type: 'dotted',
                color: '#ccc'
            }
        }
    }],
    dataZoom: [
        {
            type: '',
            height: 30,
            left: '70px',
            right: '70px',
            bottom: 28
        }
    ],
    series: [{
        type: 'bar',
        data: [300, 450, 770, 203, 255, 188, 156, -100, 20],
        barWidth: '40px',
        itemStyle: {
            normal: {
                color: '#55aee8',
                barBorderRadius: [8, 8, 8, 8],
            }
        }
    }]
}
const xData = ["2019-03-01", "2019-03-02", "2019-03-03", "2019-03-04", "2019-03-05", "2019-03-06", "2019-03-07", "2019-03-08", "2019-03-09", "2019-03-10", "2019-03-11", "2019-03-12", "2019-03-13", "2019-03-14", "2019-03-15", "2019-03-16", "2019-03-17", "2019-03-18", "2019-03-19", "2019-03-20"]
const yData1 = [12, 5, 12, 46, 22, 24, 15, 5, 54, 18, 24, 18, 31, 25, 27, 14, 15, 21, 20, 17]
const yData2 = [13, 7, 10, 38, 17, 28, 22, 12, 28, 19, 14, 19, 19, 31, 22, 11, 14, 19, 22, 16]
const yData3 = [2, 34, 16, 8, 27, 31, 12, 16, 28, 9, 3, 7, 45, 1, 39, 35, 27, 41, 36, 6]


let base = +new Date(1983, 9, 3)
const oneDay = 24 * 3600 * 1000

let areaX = []
let areaY1 = []
let areaY2 = []
let areaY3 = []
let areaY4 = []
let areaY5 = []
let areaY6 = []
let areaY7 = []
let areaY8 = []

for (let i = 0; i < 50; i++) {
    const now = new Date(base += oneDay)
    areaX.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-'))
    areaY1.push(Math.random() * 10 - 3)
    areaY2.push(Math.random() * 20 - 4)
    areaY3.push(Math.random() * 30 - 5)
    areaY4.push(Math.random() * 40 - 6)
    areaY5.push(Math.random() * 50 - 7)
    areaY6.push(Math.random() * 60 - 8)
    areaY7.push(Math.random() * 70 - 10)
    areaY8.push(Math.random() * 80 - 21)
}

const lineOptions =  {
    title: {
        top: '0',
        left: 'center'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                width: 60,
                color: 'rgba(0, 0, 0, 0.1)'
            },
            z: -1
        }
    },
    legend: {
        x: 'center',
        icon: 'line',
        bottom: 0,
        data: ['紫霄一号基金', '子轩福豆2号', '八阳6号']
    },
    dataZoom: [{
            type: 'slider',
            show: true,
            height: 30,
            left: '70px',
            right: '70px',
            bottom: '5%',
            start: 0,
            end: 100,
            textStyle: {
                color: '#999',
                fontSize: 11,
            },
        }, {
            type: 'inside'
        }

    ],
    grid: {
        right: '46px',
        bottom: '15%',
        left: '46px',
        top: '80px',
        containLabel: false
    },
    xAxis: [{
        type: 'category',
        data: xData,
        nameTextStyle: {
            color: '#999'
        },
        axisLine: {
            onZero: false,
            lineStyle: {
                color: '#ccc'
            }
        },
        axisTick: {
            show: true,
            position: 'bottom',
            inside: false
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: "#666",
                fontSize: 12,
            }
        },
    }],
    yAxis: [{
        type: 'value',
        name: '累计收益率（%）',
        nameTextStyle: {
            color: '#999'
        },
        position: 'left',
        axisLine: {
            show: false,
            lineStyle: {
                color: '#ccc',
                type: 'dotted'
            }
        },
        splitLine: {
            lineStyle: {
                type: 'solid',
                color: "#ccc",
            }

        },
        axisLabel: {
            color: '#666',
            fontSize: 12,
        }
    }, ],
    series: [{
            name: '紫霄一号基金',
            type: 'line',
            symbol: false,
            symbolSize: 0,
            lineStyle: {
                normal: {
                    shadowColor: 'rgba(0, 0, 0, 0.2)',
                    shadowOffsetY: 2,
                    shadowOffsetX: 2,
                    shadowBlur: 5
                }
            },
            itemStyle: {
                normal: {
                    color: '#ff2b2b',
                }
            },
            data: yData1
        },
        {
            name: '子轩福豆2号',
            type: 'line',
            symbol: false,
            symbolSize: 0,
            lineStyle: {
                normal: {
                    shadowColor: 'rgba(0, 0, 0, 0.2)',
                    shadowOffsetY: 2,
                    shadowOffsetX: 2,
                    shadowBlur: 5
                }
            },
            itemStyle: {
                normal: {
                    color: '#1890ff',
                }
            },
            data: yData2
        },
        {
            name: '八阳6号',
            type: 'line',
            symbol: false,
            symbolSize: 0,
            lineStyle: {
                normal: {
                    shadowColor: 'rgba(0, 0, 0, 0.2)',
                    shadowOffsetY: 2,
                    shadowOffsetX: 2,
                    shadowBlur: 5
                }
            },
            itemStyle: {
                normal: {
                    color: '#fea432',
                }
            },
            data: yData3
        }

    ]
}

const areaOptions = {
    title: {
        top: '0',
        left: 'center'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                width: 60,
                color: 'rgba(0, 0, 0, 0.1)'
            },
            z: -1
        }
    },
    legend: {
        x: 'center',
        icon: 'line',
        bottom: 0,
        data: ['紫霄一号基金', '子轩福豆2号', '八阳6号']
    },
    dataZoom: [{
            type: 'slider',
            show: true,
            height: 30,
            left: '70px',
            right: '70px',
            bottom: '5%',
            start: 0,
            end: 100,
            textStyle: {
                color: '#999',
                fontSize: 11,
            },
        }

    ],
    grid: {
        right: '46px',
        bottom: '15%',
        left: '46px',
        top: '80px',
        containLabel: false
    },
    xAxis: [{
        type: 'category',
        data: areaX,
        nameTextStyle: {
            color: '#999'
        },
        axisLine: {
            onZero: false,
            lineStyle: {
                color: '#ccc'
            }
        },
        axisTick: {
            show: true,
            position: 'bottom',
            inside: false
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: "#666",
                fontSize: 12,
            }
        },
    }],
    yAxis: [{
        type: 'value',
        name: '动态回撤（%）',
        nameTextStyle: {
            color: '#999'
        },
        position: 'left',
        axisLine: {
            show: false,
            lineStyle: {
                color: '#ccc',
                type: 'dotted'
            }
        },
        splitLine: {
            lineStyle: {
                type: 'dotted',
                color: "#ccc",
            }

        },
        axisLabel: {
            color: '#666',
            fontSize: 12,
        }
    }, ],
    series: []
}


export default class Performance extends Component {
    constructor (...props) {
        super(...props)

        this.state = {
        }
    }

    // 收益走势图
    async _getReturnOrg (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/org/getReturnOrg',
            method: 'POST',
            data: JSON.stringify({
                orgIds: query.id,
                token: cookie.get('token'),
                startLine: 0,
                navType: 'n_added_nav',
                dateRange: '2018-12-31:2019-12-31',
                compareRule: '0',
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result  = JSON.parse(data.result)

        if (result.status === 'success') {
            console.log(result, 'getReturnCal-------')
            return result.result
        } else {
            message.error('获取数据失败')
        }

    }

    // 回撤走势图
    async _getDrawdownOrg (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/org/getDrawdownOrg',
            method: 'POST',
            data: JSON.stringify({
                orgIds: query.id,
                token: cookie.get('token'),
                startLine: 0,
                navType: 'n_added_nav',
                // dateRange: '2018-12-31:2019-12-31',
                statPeriod: 'year',
                compareRule: '0',
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result  = JSON.parse(data.result)
        // console.log(result, 'getDrawdownOrg')
        if (result.status === 'success') {
            return result.result
        } else {
            message.error('获取数据失败')
        }

    }

    // 风险指标
    async _getRiskRate (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/org/getRiskOrgIndicator',
            method: 'POST',
            data: JSON.stringify({
                orgId: query.id,
                token: cookie.get('token'),
                interval: 'm3',
                benchMarkId: '1',
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result  = JSON.parse(data.result)

        if (result.status === 'success') {
            return result.result
        } else {
            message.error('获取数据失败')
        }

    }

    // 历史月度收益率
    async _getMonthReturn (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/org/monthReturn',
            method: 'POST',
            data: JSON.stringify({
                c_org_id: query.id,
                token: cookie.get('token'),
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result  = JSON.parse(data.result)

        if (result.result === 'success') {
            return result.monthReturn
        } else {
            message.error('获取数据失败')
        }

    }

    // 历史周度收益率
    async _getWeekReturn (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/org/weekReturn',
            method: 'POST',
            data: JSON.stringify({
                c_org_id: query.id,
                token: cookie.get('token'),
                compare_org_id: 'JG000003',
                beginTime: '971107200',
                endTime: '1602259200',
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result  = JSON.parse(data.result)
        if (result.result === 'success') {
            return result
        } else {
            message.error('获取数据失败')
        }

    }

    async _chartWeek () {
        const data = await this._getWeekReturn()
        const weekKeys = []
        let weekValue = []

        if (data && typeof data === 'object') {
            const resultMap = data.resMap
 
            resultMap.forEach((item, index) => {
                if (index === 0) {
                    weekValue.push({
                        name: data.orgName,
                        type: 'bar',
                        data: [],
                        barWidth: '40px',
                        itemStyle: {
                            normal: {
                                color: chartsColors[3],
                                barBorderRadius: [8, 8, 8, 8],
                            }
                        }
                    })
                } else if (index === 1) {
                    weekValue.push({
                        name: data.compareOrgName,
                        type: 'bar',
                        data: [],
                        barWidth: '40px',
                        itemStyle: {
                            normal: {
                                color:  chartsColors[4],
                                barBorderRadius: [8, 8, 8, 8],
                            }
                        }
                    })
                }
            })

            resultMap.forEach((items, ind) => {
                Object.keys(resultMap[0]).forEach((item, index) => {
                    weekKeys[index] = item
                    weekValue[ind].data[index] = items[item]
                })
            })


        }

        weekOptions.xAxis[0].data = weekKeys
        weekOptions.series = weekValue
        weekOptions.title = {
            bottom: 0,
            subtextStyle: {
                color: '#ccc'
            },
            subtext: '注：周收益率分布：通过将周度收益率平均分成 10 档（范围-1 到+1，每隔 0.2 一档，将最 大收益绝对值归 1，其他收益率归入-1 到+1 范围内），根据每档收益情况进行数量汇总，计算各档位数量占比。'
        }
        weekOptions.dataZoom[0].show = false
        this.refs.weekCharts.setBar(weekOptions)
    }

    async _chartReturn () {
        const data = await this._getReturnOrg()

        let legend = [], axisDate = [], values =[]
        if (data && typeof data === 'object') {
            legend = Object.keys(data.value)
            axisDate = data.date
            legend.forEach((item, index) => {
                values.push({
                    name: item,
                    type: 'line',
                    symbol: false,
                    symbolSize: 0,
                    lineStyle: {
                        normal: {
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                            shadowBlur: 5
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: chartsColors[index],
                        }
                    },
                    data: data.value[item]
                })
            })
            lineOptions.tooltip.formatter = (value) => {
                let itemDesc = `${value[0].name}<br />`
                value.forEach(item => {
                    itemDesc += `${item.marker}${item.seriesName}：${parseFloat(item.value).toFixed(2)}%<br />`
                })

                return itemDesc
            }
            lineOptions.legend.data = legend
            lineOptions.xAxis[0].data = axisDate
            lineOptions.series = values
            this.refs.lineChart.setOptions(lineOptions)
        }
    }

    async _chartDraw () {
        const data = await this._getDrawdownOrg()

        let legend = [], axisDate = [], values =[]
        if (data && typeof data === 'object') {
            legend = Object.keys(data.value)
            axisDate = data.date
            legend.forEach((item, index) => {
                values.push({  // 1
                    name: item,
                    type: 'line',
                    symbol: false,
                    symbolSize: 0,
                    lineStyle: {
                        normal: {
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                            shadowBlur: 5
                        }
                    },
                    areaStyle: {
                        color: areaColors[index],
                        opacity: 1
                    },
                    itemStyle: {
                        normal: {
                            color: chartsColors[index],
                        }
                    },
                    data: data.value[item]
                })
            })
            areaOptions.tooltip.formatter = (value) => {
                let itemDesc = `${value[0].name}<br />`
                value.forEach(item => {
                    itemDesc += `${item.marker}${item.seriesName}：${parseFloat(item.value).toFixed(2)}%<br />`
                })

                return itemDesc
            }
            areaOptions.dataZoom[0].height = 0
            areaOptions.dataZoom[0].width = 0
            areaOptions.legend.data = legend
            areaOptions.xAxis[0].data = axisDate
            areaOptions.series = values

        }
        this.refs.areaChart.setOptions(areaOptions)

    }
    // component did mount
    async componentDidMount () {
        await this._chartWeek()
        await this._chartDraw()
        await this._chartReturn()

        const Chart_rate = document.getElementById('lineChart')
        const Chart_area = document.getElementById('areaCharts')
        const areaContext = echarts.init(Chart_area)
        const rateContext = echarts.init(Chart_rate)
        rateContext.on('dataZoom', (e) => {
            // console.log(e)
            const batch = e.batch
            if (batch) {
                batch.forEach((item, index) => {
                    areaContext.dispatchAction({
                        type: 'dataZoom',
                        dataZoomIndex: index,
                        start: item.start,
                        end: item.end
                    })
                })
            } else {
                areaContext.dispatchAction({
                    type: 'dataZoom',
                    start: e.start,
                    end: e.end
                })
            }
            
        })

    }

    addModal () {
        this.refs.addModals._showModal()
    }

    // 没有复选框的头部
    noCheckHeader = (title) => {
        return (
            <div className='clear-fix charts_nav_header'>
                <div className='float_left'>
                    <strong className={`charts_title chart_item_title`}>{title}</strong>
                </div>
                <div className='float_right'>
                    <span className='iconfont echarts_exports iconCombinedShape'></span>
                </div>
            </div>
        )
    }
    // 排名的头部
    rankingHeader = () => {
        return (
            <div className='clear-fix charts_nav_header'>
                <div className='float_left'>

                </div>
                <div className='float_right'>
                    <span className='iconfont echarts_exports iconCombinedShape'></span>
                </div>
            </div>
        )
    }

    render () {
        const advisorName = window.localStorage.getItem('advisorName') || ''
        return (
            <div className={ProductStyle.charts_items_list}>
                <div className={ProductStyle.charts_item_bg}>
                 <CommontHeaders _addModal={this.addModal.bind(this)} _type={`advisor`} ></CommontHeaders>
                </div>
                <div className={ProductStyle.charts_item_bg}>
                    {shareHeader('单位净值走势图')}
                    <LineCharts idName={'lineChart'} ref='lineChart' />
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('回撤走势图')}
                    <AreaChart ref='areaChart' idName='areaCharts' />
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('收益-风险指标')}
                    <div className='mt_20'>
                        <RiskTable _riskType={`advisor`} productName={advisorName} _initRateRisk={this._getRiskRate.bind(this)} />
                    </div>
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('月度收益率')}
                    <div className='mt_20'>
                        <MonthTable _historyRate={this._getMonthReturn.bind(this)} dataSource={[]} />
                    </div>
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('周收益率分布')}
                    <BarCharts ref='weekCharts' />
                </div>

                <AddModal ref='addModals' />

            </div>
        )
    }
}

